import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {View, Block, Navigator} from '@tarojs/components'
import {AtButton} from 'taro-ui'
import {http} from '../../../utils/http'
import {BASE_URL, FACE} from '../../../constants/api'
import {user} from '../../../utils/user.service'
import {h5Wx} from "../../../utils/h5.service";
import {vcmonitor} from "../../../utils/tools";
import {newHttp} from "../../../utils/request";
import GzhAuth from "../../../components/gzh-auth/gzh-auth"
import {lxH5Wx} from "../../../utils/lx.h5.service";
import './face.scss'

export default class Face extends Component {
  state: {
    idnLoading: boolean
    tipsShow: boolean
    upCount: number
  } = {
    idnLoading: false,
    tipsShow: false,
    upCount: 1
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.switchTab({url: '/pages/my/index/index'})
      }, 1500)
      return
    }
  }

  async componentDidShow() {
    vcmonitor(this)
  }

  uplodeImg() {
    const that = this
    const {upCount, tipsShow} = this.state
    this.setState({idnLoading: true})
    if (process.env.TARO_ENV === 'h5') {
      if (process.env.P_ENV === 'lx') {
        lxH5Wx.chooseImage(async (files, length) => {
          lxH5Wx.uploadFace(files, length, (data) => {
            Taro.setStorageSync("faceUrl", data)
            const time = setTimeout(() => {
              Taro.navigateBack({
                delta: 1
              });
              clearTimeout(time)
            }, 500)
          })
        }, 1)
      } else {
        h5Wx.chooseImage(1, async ret => {
          Taro.showToast({
            title: '识别中...',
            icon: 'loading',
            mask: true,
            duration: 10000
          })
          h5Wx.wxuploadImage(ret, async res => {
            const data = await newHttp.catchPost(BASE_URL + FACE, {media_id: res}, true)
            if (data.status == 400) {
              that.setState({tipsShow: true})
              Taro.showToast({
                title: data.message,
                icon: 'none'
              })
              return
            }
            that.setState({tipsShow})
            Taro.setStorageSync("faceUrl", data.domain + data.url)
            const time = setTimeout(() => {
              Taro.navigateBack({
                delta: 1
              });
              clearTimeout(time)
            }, 500)
            Taro.hideToast();
          })
        })
      }
    } else {
      Taro.chooseImage({
        count: upCount,  //最多可以选择的图片总数
        sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          const tempFilePaths = res.tempFilePaths;
          //启动上传等待中...
          Taro.showToast({
            title: '识别中...',
            icon: 'loading',
            mask: true,
            duration: 10000
          })
          for (let i = 0, h = tempFilePaths.length; i < h; i++) {
            Taro.uploadFile({
              url: BASE_URL + FACE,
              filePath: tempFilePaths[i],
              name: 'face',
              formData: {
                'imgIndex': i
              },
              header: http.getHeader(),
              success: function (res) {
                const data = JSON.parse(res.data);
                if (res.statusCode == 400) {
                  that.setState({tipsShow: true})
                  Taro.showToast({
                    title: data.message,
                    icon: 'none'
                  })
                  return
                }
                //如果是最后一张,则隐藏等待中
                that.setState({tipsShow})
                Taro.setStorage({
                  key: 'faceUrl',
                  data: data.data.domain + data.data.url,
                })
                if (data.data.domain && data.data.url) {
                  const pages = Taro.getCurrentPages()
                  const prevPage = pages[pages.length - 2]
                  if (prevPage) {
                    prevPage.setData({face_url: data.data.domain + data.data.url}, () => {
                      Taro.navigateBack({
                        delta: 1
                      })
                    })
                  } else {
                    Taro.showToast({title: '错误操作'})
                  }
                  Taro.hideToast();
                }
              },
              fail: function (res) {
                Taro.hideToast();
                Taro.showModal({
                  title: '错误提示',
                  content: '上传图片失败',
                  showCancel: false
                })
              }
            })
          }
        }
      })
    }
  }

  render() {
    const {idnLoading, tipsShow} = this.state
    return (
      <View className='face-wrapper'>
        <GzhAuth />
        <View className='head'>
          <View className={`head_bg ${idnLoading ? 'head_bg_active' : ''}`}>
            {tipsShow && <Block>
              <View className='tips'>未识别成功</View>
              <View className='tips'>请重新操作!</View>
            </Block>}
          </View>
          <View className='tips_one'>请拍摄或上传正面免冠素颜人像照片</View>
          <Navigator className='tips_two' url='/main/my/face/example' hoverClass='none'>
            <View className='tips_two'>查看示例</View>
          </Navigator>
        </View>
        <View className='btn_box'>
          <AtButton onClick={this.uplodeImg.bind(this)} className='btn1'>拍照</AtButton>
          <AtButton onClick={this.uplodeImg.bind(this)} type='secondary' className='btn2'>从手机相册选择</AtButton>
        </View>
      </View>
    )
  }
}
